const path = require('path');
var fs=require('fs');
var cache={};
function store(key,value){
	//normalize将传入的路径转换为标准路径
	//win下为\，linux下为/
	//想要默认显示为/的话，需要替换.replace(/\\/g,'/')
	cache[path.normalize(key)]=value;
}

store('foo/bar',1);
store('foo//baz//../bar',2);
console.log(cache);
//拼接路径
console.log(path.join('foo/','baz/','../bar'));
//获取扩展名
console.log(path.extname('foo/bar.js'));

//遍历目录
//递归算法简洁，但是每次产生一次函数调用，
//考虑性能的时候需要把递归算法转换为循环算法，以减少行数调用次数

//遍历推荐使用深度优先+先序遍历算法
//同步遍历
function travel(dir,callback){
	fs.readdirSync(dir).forEach(function (file){
		var pathname=path.join(dir,file);
		if(fs.statSync(pathname).isDirectory()){
			//如果找到新的目录，则先去这个目录里面查找
			travel(pathname,callback);
		}else{
			callback(pathname);
		}
	});
}
var t1=Date.now();
travel('/Users/italks/Documents/GitHub/nodejs/nodejstest',function (pathname){
	console.log(pathname);
});
var t2=Date.now();
console.log(t2-t1);

//异步遍历
//运行异常？？？？？
function travel1(dir,callback,finish){
	fs.readdir(dir,function(err,files){
		(function next(i){
			if(i<files.length){
				var pathname=path.join(dir,files[i]);

				fs.stat(pathname,function(err,stats){
					if(stats.isDirectory()){
						travel1(pathname,callback,function(){
							next(i+1);
						});
					}else{
						callback(pathname,function(){
							next(i+1);
						});
					}
				});
			}else{
				finish&&finish();
			}
		}(1));
	});
}
var t1=Date.now();
travel1('/Users/italks/Documents/GitHub/nodejs/nodejstest',function (pathname){
	console.log(pathname);
});
var t2=Date.now();
console.log(t2-t1);



